﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore读写分离.DAL
{
    public class SlaveRoundRobin
    {
        private List<string> _slaveConnections;
        // 当前轮询的连接索引
        private int _index = -1;

        public SlaveRoundRobin(DbConnectionOptions connectionOptions)
        {
            if (connectionOptions.SlaveConnections.Count == 0)
                throw new Exception("slave connections can't be null");
            _slaveConnections = connectionOptions.SlaveConnections.ToList();
        }

        public string NextSlave()
        {
            _index = Interlocked.Increment(ref _index) % _slaveConnections.Count;
            return _slaveConnections[_index];
        }
    }
}
